const https = require('https');
///雪花算法生成id
const snowflake = require('./snowflake')
const SQLHelper = require('./SQLHelper')
const { formatTime } = require('./util')




module.exports = function(app){
  module.exports = function(app){
    ///登录拦截中间件
function loginRouter(req,res,next){
    let token = req.headers.token
    if(token){
        SQLHelper(`select * from session where id = ${token}`).then(ret => {
            if(ret.length){
                let session = ret[0]
                req.session = {
                    userId:session.userId,
                    userName:session.userName
                }
                next()
            }else{
                res.status(406).send({errorMsg:'当前用户未登录'})
            }
        })
    }else{
        res.status(405).send({errorMsg:'缺少token，请先进行登录'})
    }
  }
  
  
  ///让初登陆以为的所有小程序接口都先验证登陆
  app.use('/wx',loginRouter)
  
 
  
//   //解析body中间件
//   app.use(bodyParser.json({limit:'100mb'}))
  
  
  // 微信登陆
  app.get('/wx/login', (req, res) => {
    let code = req.query.code
    let appid = 'wx960d8889c74b6ef7'
    let secret = 'e6b657e9ab5eed4275826534c3fe1ebf'
    https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
      ret.on('data', (ret) => {
        ret = JSON.parse(ret.toString())
        let openid = ret.openid
        if(!openid){
            res.send({errorMsg: ret.errMsg || '获取openid错误'})
        }else{
            ///查询用户是否已经注册
            let queryMember = `select * from member where openId = '${openid}'`
            SQLHelper(queryMember).then(membersRet => {
                if(membersRet.length){///用户已经存在
                    ///挂载到req
                    req.member = membersRet[0]
                    next()
                }else{///用户不存在,使用openid注册用户
                    SQLHelper(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember => {
                        ///注册成功返回新用户信息
                        SQLHelper(queryMember).then(newMember => {
                            ///挂载到req
                            req.member = membersRet[0]
                            next()
                        })
                    })
                }
            })
        }
    });
  
  }).on('error', (e) => {
    console.error(e)
    res.send({errorMsg:'获取openid错误'})
  });
  },(req,res) => {
  let member = req.member
  let token = snowflake()
  ///缓存token到session表
  SQLHelper(`
  INSERT INTO session(id,userId,userName,inTime,platform) 
  VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
  `).then(ret => {
    res.send({
        nickName:member.nickName,
        token,
        openId:member.openId,
        avatarUrl:member.avatarUrl,
        _id:member._id
    })
  })
  })

}
}